namespace dotnet_ef_admin.Src.Extensions;

using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;


/// <summary>
/// 异常处理中间件，用于捕获和处理整个请求管道中的异常。
/// </summary>
public class ExceptionHandlingMiddleware {
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionHandlingMiddleware> _logger;

    /// <summary>
    /// 初始化异常处理中间件的新实例。
    /// </summary>
    /// <param name="next">请求委托。</param>
    /// <param name="logger">日志记录器。</param>
    public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger) {
        _next = next;
        _logger = logger;
    }

    /// <summary>
    /// 异常处理逻辑。
    /// </summary>
    /// <param name="context">HTTP上下文。</param>
    public async Task InvokeAsync(HttpContext context) {
        try {
            // 继续处理请求
            await _next(context);
        } catch (Exception ex) {
            // 记录异常日志
            // _logger.LogError(ex, "发生了未处理的异常。");
            // 处理异常并返回响应
            await HandleExceptionAsync(context, ex);
        }
    }

    /// <summary>
    /// 处理异常并返回标准化的错误响应。
    /// </summary>
    /// <param name="context">HTTP上下文。</param>
    /// <param name="exception">捕获的异常。</param>
    /// <returns>任务对象，表示异步操作的完成。</returns>
    private static Task HandleExceptionAsync(HttpContext context, Exception exception) {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        var result = JsonSerializer.Serialize(new {
            code = -1,
            data = (object?)null,
            msg = exception.Message
        });
        return context.Response.WriteAsync(result);
    }
}
